#ifndef NETWORKSERVICES_EVENTLOOP_H
#define NETWORKSERVICES_EVENTLOOP_H

#include <mutex>
#include <memory>
#include <vector>
#include <atomic>
#include <queue>
#include <functional>
#include <unordered_map>

class Epoll;
class Channel;
class Connection;

class EventLoop {
public:
    static int CreateTimerFd(int sec = 30);

    EventLoop(bool mainloop, int timetvl = 30, int timeout = 80);
    ~EventLoop();
    void Run();
    void Stop();
    void WakeUp() const;
    void HandleWakeUp();
    void HandleTimer();
    void OnConnection(std::shared_ptr<Connection>& ptr);
    void UpdateChannel(Channel *ch);                        // 把channel添加/更新到红黑树上，channel中有fd，也有需要监视的事件。
    void RemoveChannel(Channel *ch);
    void QueueInLoop(const std::function<void()>& fn);
    bool IsInLoopThread() const;

public:
    std::function<void(EventLoop *)> onEpollTimeout;
    std::function<void(int)> onTimer;

private:
    int timetvl;
    int connectionTimeout;
    int wakeupFd;
    int timerFd;
    bool mainLoop;              // true-是主事件循环，false-是从事件循环。
    long int threadId{};
    std::atomic<bool> isStop;
    std::queue<std::function<void()>> taskQueue;
    std::unordered_map<int, std::shared_ptr<Connection>> conns;
    std::mutex queueMutex;
    std::mutex mapMutex;
    std::unique_ptr<Epoll> ep;
    std::unique_ptr<Channel> wakeChannel;
    std::unique_ptr<Channel> timerChannel;
};


#endif // NETWORKSERVICES_EVENTLOOP_H
